local function addLuaPath(path)
	package.path = string.format("%s;%s/?.lua;%s/?/init.lua;%s/lua/?.lua;%s/lua/?/init.lua",package.path, path, path, path, path)
end
local function addLuaCpath(path)
	local osType = os.getenv("OS")
	if nil ~= osType then
		local startPos,_ = string.find(osType,"Windows")
		if nil ~= startPos then
			package.cpath = string.format("%s;%s/?.dll;%s/?51.dll;%s/clibs/?.dll;%s/clibs/?51.dll",package.cpath, path, path, path, path)
		else
			package.cpath = string.format("%s;%s/?.so;%s/?51.so;%s/clibs/?.so;%s/clibs/?51.so",package.cpath, path, path, path, path)
		end
	else
		package.cpath = string.format("%s;%s/?.so;%s/?51.so;%s/clibs/?.so;%s/clibs/?51.so",package.cpath, path, path, path, path)
	end
end

local root = "."

addLuaPath(root .. "/lualib")
addLuaCpath(root .. "/lualib")

local http = require("http")
local pp = require('pretty-print')
local uvContainer = require("uv-container")
local getDispatcher = require("luv-http.dispatcher")
local getRouteHandlers = require("luv-http.route-handler")
local getStaticHandler = require("luv-http.static-handler")

local envCfg = require(root .. '/conf')(root)
local port = envCfg.port
local appRoot = envCfg.appRoot
local appCfg = require(appRoot .. "/web")({
    root = appRoot
})

if appCfg.lualib then
    addLuaPath(appCfg.lualib)
end
if appCfg.clib then
    addLuaCpath(appCfg.clib)
end

local ctx = {
    envCfg = envCfg, --环境配置
    appCfg = appCfg, --应用配置
    data = {} --实例数据
}

--load listener
if appCfg.listeners and appCfg.listeners.onBeforeStart then
    for index, listener in ipairs(appCfg.listeners.onBeforeStart) do
        local clazz = require(listener.handler)
        clazz.new(ctx, listener.initParam)
    end
end

local wsRouteHandlers = getRouteHandlers(ctx, appCfg.wsRoutes, true)
local routeHandlers = getRouteHandlers(ctx, appCfg.routes)
local staticHandler = getStaticHandler(appCfg.static)
local appFilters = appCfg.filters
if not appFilters then
    appFilters = {}
end
local filters = {}
--添加业务过滤器
for _, appFilter in ipairs(appFilters) do
    local clazz = require(appFilter.handler)
    local inst = clazz.new(ctx, appFilter.initParam)
    table.insert(filters, inst)
end
local dispatcher = getDispatcher(filters, wsRouteHandlers, routeHandlers, staticHandler)

local function onRequest(req, resp)
    dispatcher(req, resp, ctx)
end

uvContainer(function ()

    --load listener
    if appCfg.listeners and appCfg.listeners.onAfterStart then
        for index, listener in ipairs(appCfg.listeners.onAfterStart) do
            local clazz = require(listener.handler)
            clazz.new(ctx, listener.initParam)
        end
    end

	http.createServer(onRequest):listen(port)
	pp.print("Server listening at http://localhost:" .. port .. "/")

end)